import { defineStore } from 'pinia';
import { showToast } from '@/utils/toast';
import {
  getUsers as getUsersApi,
  getCurrentUser as getCurrentUserApi,
  createUser as createUserApi,
  updateUser as updateUserApi,
  deleteUser as deleteUserApi,
  batchDeleteUsers as batchDeleteUsersApi,
  toggleUserStatus as toggleUserStatusApi,
  updateUserRole as updateUserRoleApi,
  resetUserPassword as resetUserPasswordApi
} from '@/api/user';
import {
  getRoles as getRolesApi,
  createRole as createRoleApi,
  updateRole as updateRoleApi,
  deleteRole as deleteRoleApi
} from '@/api/auth';

// 用户管理状态仓库
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户列表
    users: [],
    // 角色列表
    roles: [],
    // 当前登录用户
    currentUser: null,
    // 加载状态
    loading: {
      users: false,
      roles: false,
      submit: false,
      currentUser: false
    },
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filters: {
      keyword: '',
      roleId: '',
      status: ''
    }
  }),

  getters: {
    // 获取用户数量
    userCount: (state) => state.users.length,
    
    // 根据ID获取用户
    getUserById: (state) => (id) => {
      return state.users.find(user => user.id === id) || null;
    },
    
    // 根据角色ID获取用户
    getUsersByRoleId: (state) => (roleId) => {
      return state.users.filter(user => user.roleId === roleId);
    },
    
    // 获取活跃用户数量
    activeUserCount: (state) => {
      return state.users.filter(user => user.status === 'active').length;
    },
    
    // 获取角色数量
    roleCount: (state) => state.roles.length,
    
    // 根据ID获取角色
    getRoleById: (state) => (id) => {
      return state.roles.find(role => role.id === id) || null;
    }
  },

  actions: {
    /**
     * 获取用户列表
     */
    async getUsers() {
      try {
        this.loading.users = true;
        const response = await getUsersApi({
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          keyword: this.filters.keyword,
          roleId: this.filters.roleId,
          status: this.filters.status
        });
        
        this.users = response.users || [];
        this.pagination.total = response.total || 0;
        return this.users;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        showToast('获取用户列表失败', 'error');
        return [];
      } finally {
        this.loading.users = false;
      }
    },
    
    /**
     * 获取所有角色
     */
    async getRoles() {
      try {
        this.loading.roles = true;
        const response = await getRolesApi();
        this.roles = response || [];
        return this.roles;
      } catch (error) {
        console.error('获取角色列表失败:', error);
        showToast('获取角色列表失败', 'error');
        return [];
      } finally {
        this.loading.roles = false;
      }
    },
    
    /**
     * 获取当前登录用户信息
     */
    async getCurrentUser() {
      try {
        this.loading.currentUser = true;
        const response = await getCurrentUserApi();
        this.currentUser = response || null;
        return this.currentUser;
      } catch (error) {
        console.error('获取当前用户信息失败:', error);
        showToast('获取当前用户信息失败', 'error');
        return null;
      } finally {
        this.loading.currentUser = false;
      }
    },
    
    /**
     * 创建用户
     * @param {Object} user - 用户数据
     */
    async createUser(user) {
      try {
        this.loading.submit = true;
        const newUser = await createUserApi(user);
        
        // 更新本地状态
        this.users.push(newUser);
        this.pagination.total++;
        
        showToast('用户创建成功', 'success');
        return newUser;
      } catch (error) {
        console.error('创建用户失败:', error);
        showToast(error.response?.data?.message || '创建用户失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新用户
     * @param {string|number} id - 用户ID
     * @param {Object} user - 用户数据
     */
    async updateUser(id, user) {
      try {
        this.loading.submit = true;
        const updatedUser = await updateUserApi(id, user);
        
        // 更新本地状态
        const index = this.users.findIndex(u => u.id === id);
        if (index !== -1) {
          this.users[index] = { ...this.users[index], ...updatedUser };
        }
        
        // 如果是当前用户更新，也要更新当前用户信息
        if (this.currentUser && this.currentUser.id === id) {
          this.currentUser = { ...this.currentUser, ...updatedUser };
        }
        
        showToast('用户更新成功', 'success');
        return updatedUser;
      } catch (error) {
        console.error(`更新用户${id}失败:`, error);
        showToast(error.response?.data?.message || '更新用户失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 删除用户
     * @param {string|number} id - 用户ID
     */
    async deleteUser(id) {
      try {
        this.loading.submit = true;
        await deleteUserApi(id);
        
        // 更新本地状态
        this.users = this.users.filter(user => user.id !== id);
        this.pagination.total--;
        
        showToast('用户删除成功', 'success');
        return true;
      } catch (error) {
        console.error(`删除用户${id}失败:`, error);
        showToast(error.response?.data?.message || '删除用户失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 批量删除用户
     * @param {Array} ids - 用户ID数组
     */
    async batchDeleteUsers(ids) {
      try {
        this.loading.submit = true;
        await batchDeleteUsersApi(ids);
        
        // 更新本地状态
        this.users = this.users.filter(user => !ids.includes(user.id));
        this.pagination.total -= ids.length;
        
        showToast(`成功删除${ids.length}个用户`, 'success');
        return true;
      } catch (error) {
        console.error('批量删除用户失败:', error);
        showToast(error.response?.data?.message || '批量删除用户失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 切换用户状态（启用/禁用）
     * @param {string|number} id - 用户ID
     * @param {boolean} active - 是否启用
     */
    async toggleUserStatus(id, active) {
      try {
        this.loading.submit = true;
        const updatedUser = await toggleUserStatusApi(id, { status: active ? 'active' : 'inactive' });
        
        // 更新本地状态
        const index = this.users.findIndex(user => user.id === id);
        if (index !== -1) {
          this.users[index] = { ...this.users[index], ...updatedUser };
        }
        
        showToast(`用户${active ? '启用' : '禁用'}成功`, 'success');
        return updatedUser;
      } catch (error) {
        console.error(`切换用户${id}状态失败:`, error);
        showToast(error.response?.data?.message || '切换用户状态失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 创建角色
     * @param {Object} role - 角色数据
     */
    async createRole(role) {
      try {
        this.loading.submit = true;
        const newRole = await createRoleApi(role);
        
        // 更新本地状态
        this.roles.push(newRole);
        
        showToast('角色创建成功', 'success');
        return newRole;
      } catch (error) {
        console.error('创建角色失败:', error);
        showToast(error.response?.data?.message || '创建角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新角色
     * @param {string|number} id - 角色ID
     * @param {Object} role - 角色数据
     */
    async updateRole(id, role) {
      try {
        this.loading.submit = true;
        const updatedRole = await updateRoleApi(id, role);
        
        // 更新本地状态
        const index = this.roles.findIndex(r => r.id === id);
        if (index !== -1) {
          this.roles[index] = { ...this.roles[index], ...updatedRole };
        }
        
        showToast('角色更新成功', 'success');
        return updatedRole;
      } catch (error) {
        console.error(`更新角色${id}失败:`, error);
        showToast(error.response?.data?.message || '更新角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 删除角色
     * @param {string|number} id - 角色ID
     */
    async deleteRole(id) {
      try {
        this.loading.submit = true;
        await deleteRoleApi(id);
        
        // 更新本地状态
        this.roles = this.roles.filter(role => role.id !== id);
        // 同时将拥有该角色的用户角色置空或设为默认角色
        this.users = this.users.map(user => 
          user.roleId === id ? { ...user, roleId: null } : user
        );
        
        showToast('角色删除成功', 'success');
        return true;
      } catch (error) {
        console.error(`删除角色${id}失败:`, error);
        showToast(error.response?.data?.message || '删除角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新用户角色
     * @param {string|number} userId - 用户ID
     * @param {string|number} roleId - 角色ID
     */
    async updateUserRole(userId, roleId) {
      try {
        this.loading.submit = true;
        const updatedUser = await updateUserRoleApi(userId, { roleId });
        
        // 更新本地状态
        const index = this.users.findIndex(user => user.id === userId);
        if (index !== -1) {
          this.users[index] = { ...this.users[index], ...updatedUser };
        }
        
        // 如果是当前用户更新，也要更新当前用户信息
        if (this.currentUser && this.currentUser.id === userId) {
          this.currentUser = { ...this.currentUser, roleId };
        }
        
        showToast('用户角色更新成功', 'success');
        return updatedUser;
      } catch (error) {
        console.error(`更新用户${userId}角色失败:`, error);
        showToast(error.response?.data?.message || '更新用户角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 重置用户密码
     * @param {string|number} userId - 用户ID
     * @param {string} newPassword - 新密码
     */
    async resetUserPassword(userId, newPassword) {
      try {
        this.loading.submit = true;
        await resetUserPasswordApi(userId, { newPassword });
        
        showToast('密码重置成功', 'success');
        return true;
      } catch (error) {
        console.error(`重置用户${userId}密码失败:`, error);
        showToast(error.response?.data?.message || '密码重置失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新筛选条件
     * @param {Object} filters - 筛选条件
     */
    updateFilters(filters) {
      this.filters = { ...this.filters, ...filters };
      // 重置页码
      this.pagination.page = 1;
      // 重新获取用户列表
      this.getUsers();
    },
    
    /**
     * 更新分页信息
     * @param {Object} pagination - 分页信息
     */
    updatePagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
      // 重新获取用户列表
      this.getUsers();
    },
    
    /**
     * 清除用户状态（登出时使用）
     */
    clearUserState() {
      this.currentUser = null;
      // 可以根据需要清除其他状态
    }
  }
});